package com.hos.db.manager;

import com.gexin.rp.sdk.base.uitls.MD5Util;
import com.hos.db.create.user.UserPatTable;
import com.hos.db.entity.UserPatsEntity;
import com.hos.db.entity.pat.UserPatLoginEntity;
import com.hos.net.req.pat.PatRegisterReq;
import com.hos.net.req.pat.PatUpdateReq;
import com.hos.net.req.pat.PatWXLoginReq;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.utile.DLog;
import com.hos.utile.DateUtile;
import com.hos.utile.Md5Utile;
import com.hos.utile.StringUtile;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PatsManager {

    private static PatsManager userPatsManager;

    public static PatsManager getInstance() {
        if (userPatsManager == null) {
            userPatsManager = new PatsManager();
        }
        return userPatsManager;
    }

    //获取推送id
    public String getPushId(JdbcTemplate jdbcTemplate, String patId) {
        UserPatsEntity user = null;
        String sql = "SELECT * FROM " + UserPatTable.tableName + " WHERE "
                + UserPatTable.tablePatId + " = '" + patId + "'";
        List<UserPatsEntity> users = userQuery(jdbcTemplate, sql);
        String pushId = "";
        if (users != null && users.size() > 0) {
            pushId = users.get(0).getPatPushid();
        }
        return pushId;
    }

    /**
     * 按手机号获取用户
     *
     * @param jdbcTemplate
     * @param phone
     * @return
     */
    public UserPatsEntity getUserForPhone(JdbcTemplate jdbcTemplate, String phone) {
        UserPatsEntity user = null;
        String sql = "SELECT * FROM " + UserPatTable.tableName + " WHERE "
                + UserPatTable.tablePatPhone + " = " + phone;
        List<UserPatsEntity> users = userQuery(jdbcTemplate, sql);
        if (users != null && users.size() > 0) {
            user = users.get(0);
        }
        return user;
    }

    /**
     * 手机号注册
     *
     * @param jdbcTemplate
     * @param req          用户注册参数
     * @return 注册结果
     */
    public String userRegisterReq(JdbcTemplate jdbcTemplate, PatRegisterReq req) {
        boolean isExit = isRegister(jdbcTemplate, req.account);
        if (isExit) {
            return new MsgHint("该账号已存在").toJson();
        }
        String response = new MsgHint("注册失败").toJson();
        String patId = Md5Utile.encode(req.account);
        String sql = "INSERT INTO " + UserPatTable.tableName
                + "("
                + UserPatTable.tablePatId + ","
                + UserPatTable.tablePatName + ","
                + UserPatTable.tablePatAccount + ","
                + UserPatTable.tablePatPwd + ","
                + UserPatTable.tablePatPhone + ","
                + UserPatTable.tablePatPortrait + ","
                + UserPatTable.tablePatToken + ","
                + UserPatTable.tablePatLoninTime + ","
                + UserPatTable.tablePatRegisterTime
                + ")"
                + " VALUES (?,?, ?, ?,?, ?,?, ?, ?)";
        try {
            String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
            String token = MD5Util.getMD5Format(req.account + loginTime);
            //
            int status = jdbcTemplate.update(sql,
                    new Object[]{patId, req.name, req.account, MD5Util.getMD5Format(req.pwd),
                            req.account, req.patHead, token, loginTime, new Date()});
            if (status > 0) {
                UserPatLoginEntity user = new UserPatLoginEntity();
                user.setPatId(patId);
                user.setPatAccount(req.account);
                user.setPatName(req.name);
                user.setPatPhone(req.account);
                user.setPatPortrait(req.patHead);
                user.setPatToken(token);
                BaseResponse res = new BaseResponse();
                res.obj = user;
                response = res.toJson("0", "注册成功");
            }
        } catch (Exception e) {
            DLog.e("注册失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 按手机号码登录
     *
     * @param jdbcTemplate jdbc
     * @param patPhone     登录账户
     * @return
     */
    public String userLoginReq(JdbcTemplate jdbcTemplate, String patPhone, String patPwd, String pushId) {
        patPwd = MD5Util.getMD5Format(patPwd);
        String sql = "SELECT * FROM " + UserPatTable.tableName + " WHERE "
                + UserPatTable.tablePatPhone + " = " + patPhone + " and "
                + UserPatTable.tablePatPwd + " = " + "'" + patPwd + "'";
        DLog.e(sql);
        List<UserPatLoginEntity> users = userQueryLogin(jdbcTemplate, sql);
        if (users == null || users.size() == 0) {
            return new MsgHint("账号或者密码错误").toJson();
        }
        String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
        String token = MD5Util.getMD5Format(patPhone + loginTime);
        UserPatLoginEntity user = users.get(0);
        user.setPatToken(token);
        createToken(jdbcTemplate, patPhone, token, loginTime, pushId);
        //
        BaseResponse<UserPatLoginEntity> baseResponse = new BaseResponse();
        baseResponse.obj = user;
        baseResponse.token = token;
        return baseResponse.toJson("0", "登录成功");
    }

    //微信登录
    public String userWXLoginReq(JdbcTemplate jdbcTemplate, PatWXLoginReq req) {
        String sql = "SELECT * FROM " + UserPatTable.tableName + " WHERE "
                + UserPatTable.tablePatWXId + " = " + req.patWxId;
        List<UserPatLoginEntity> users = userQueryLogin(jdbcTemplate, sql);
        UserPatLoginEntity pat = null;
        if (users != null && users.size() > 0) {
            pat = users.get(0);
            String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
            String token = MD5Util.getMD5Format(req.patWxId + loginTime);
            createTokenWx(jdbcTemplate, req.patWxId, token, loginTime);
            pat.setPatToken(token);
        }
        if (pat == null) {
            String patId = Md5Utile.encode(req.patWxId);
            sql = "INSERT INTO " + UserPatTable.tableName
                    + "("
                    + UserPatTable.tablePatId + ","
                    + UserPatTable.tablePatWXId + ","
                    + UserPatTable.tablePatAccount + ","
                    + UserPatTable.tablePatName + ","
                    + UserPatTable.tablePatPortrait + ","
                    + UserPatTable.tablePatToken + ","
                    + UserPatTable.tablePatLoninTime + ","
                    + UserPatTable.tablePatRegisterTime
                    + ")"
                    + " VALUES (?,?,?,?, ?,?, ?,?)";
            String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
            String token = MD5Util.getMD5Format(req.patWxId + loginTime);
            int status = jdbcTemplate.update(sql,
                    new Object[]{patId, req.patWxId, req.patWxId, req.patWxName, req.patWxHead
                            , token, loginTime, new Date()});
            if (status > 0) {
                //微信登录成功
                pat = new UserPatLoginEntity();
                pat.setPatName(req.patWxName);
                pat.setPatPortrait(req.patWxHead);
                pat.setPatToken(token);
                pat.setPatWxId(req.patWxId);
            } else {
                return new MsgHint("微信登录失败").toJson();
            }

        }
        return pat.toJson("登录成功");
    }

    public String updatePushId(JdbcTemplate jdbcTemplate, String patId, String pushId) {
        String sql = "UPDATE " + UserPatTable.tableName
                + " SET "
                + UserPatTable.tablePatPushId + " = '" + pushId + "'"
                + " WHERE "
                + UserPatTable.tablePatId + " = '" + patId + "'";
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "更新失败").toJson();
        }
        return new MsgHint("更新成功").toJson();
    }

    /**
     * 微信账号绑定手机号码
     *
     * @param jdbcTemplate
     * @param
     * @return
     */
    public String updateWxBoundPhone(JdbcTemplate jdbcTemplate, String wxId, String phone) {
        String sql = "UPDATE " + UserPatTable.tableName
                + " SET "
                + UserPatTable.tablePatPhone + " = '" + phone + "'"
                + " WHERE "
                + UserPatTable.tablePatWXId + " = '" + wxId + "'";

        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "绑定成功").toJson();
        }
        return new MsgHint("绑定失败").toJson();
    }

    //重置密码
    public String updateRestPwdReq(JdbcTemplate jdbcTemplate, String phone, String pwd) {
        String sql = "UPDATE " + UserPatTable.tableName
                + " SET "
                + UserPatTable.tablePatPwd + " = '" + Md5Utile.encode(pwd) + "'"
                + " WHERE "
                + UserPatTable.tablePatPhone + " = " + phone;
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "修改成功").toJson();
        }
        return new MsgHint("修改失败").toJson();
    }

    /**
     * @param jdbcTemplate jdbc
     * @param account   查询账号
     * @return true 账号存在
     */
    /**
     * @param jdbcTemplate jdbc
     * @param patAccount   查询账号
     * @return true 账号存在
     */
    public boolean isRegister(JdbcTemplate jdbcTemplate, String patAccount) {
        String sql = "SELECT * FROM " + UserPatTable.tableName + " WHERE "
                + UserPatTable.tablePatAccount + " = " + patAccount;
        List<UserPatsEntity> users = userQuery(jdbcTemplate, sql);
        return users != null && users.size() > 0;
    }


    /**
     * 获取患者
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     * @param hasNextPage  判断是否有下一页
     */
    public List<UserPatsEntity> getPats(JdbcTemplate jdbcTemplate, int pageNo, int pageSize,
                                        boolean hasNextPage) {
        //SELECT column_name,column_name FROM table_name [WHERE Clause] [LIMIT N][ OFFSET M]
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        //排序
        //SELECT * FROM user ORDER BY create_time,id LIMIT 6,2;
        String sql = "SELECT * FROM " + UserPatTable.tableName
                + " ORDER BY " + UserPatTable.tablePatRegisterTime
                + " DESC "
                // + "," + UserPatTable.tableId
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<UserPatsEntity> user = userQuery(jdbcTemplate, sql);
        if (user == null) {
            user = new ArrayList();
        }
        return user;
    }

    public List<UserPatsEntity> getPats(JdbcTemplate jdbcTemplate, String key, int pageNo, int pageSize,
                                        boolean hasNextPage) {

        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String where = "";
        if (key != null && !key.equals("")) {
            where = " WHERE " + UserPatTable.tablePatPhone + " LIKE '%" + key + "%' "
                    + " OR " + UserPatTable.tablePatName + " LIKE '%" + key + "%' ";
        }
        String sql = "SELECT * FROM " + UserPatTable.tableName
                + where
                + " ORDER BY " + UserPatTable.tablePatRegisterTime
                + " DESC "
                //+ "," + UserDocTable.tableId
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        DLog.e("sql:" + sql);
        List<UserPatsEntity> user = userQuery(jdbcTemplate, sql);
        if (user == null) {
            user = new ArrayList();
        }
        return user;
    }

    public int getPats(JdbcTemplate jdbcTemplate, String key) {
        if (key != null && !key.equals("")) {
            return getPats(jdbcTemplate);
        }
        String sql = "SELECT count(*) FROM " + UserPatTable.tableName
                + " WHERE " + UserPatTable.tablePatPhone + " LIKE '%" + key + "%' "
                + " OR " + UserPatTable.tablePatName + " LIKE '%" + key + "%' ";
        int count = jdbcTemplate.queryForInt(sql);
        return count;
    }

    public int getPats(JdbcTemplate jdbcTemplate) {
        //select count(*) from user_docs
        String sql = "SELECT count(*) FROM " + UserPatTable.tableName;
        int count = jdbcTemplate.queryForInt(sql);
        return count;
    }

    //修改患者信息
    public String updateUserReq(JdbcTemplate jdbcTemplate, PatUpdateReq pat) {
        String update = "";
        String name = pat.patName;
        if (name != null && name != "") {
            update += " , " + UserPatTable.tablePatName + " = '" + name + "'";
        }
        String patPhone = pat.patPhone;
        if (patPhone != null && patPhone != "") {
            update += " , " + UserPatTable.tablePatPhone + " = '" + patPhone + "'";
        }
        String patHaed = pat.patHead;
        if (patHaed != null && patHaed != "") {
            update += " , " + UserPatTable.tablePatPortrait + " = '" + patHaed + "'";
        }
        Integer patState = pat.patState;
        if (patState != null && (patState == 1 || patState == 2)) {
            update += " , " + UserPatTable.tablePatState + " = '" + patState + "'";
        }
        String patSex = pat.patSex;
        if (patHaed != null ) {
            update += " , " + UserPatTable.tablePatSex + " = '" + patSex + "'";
        }
        String patBirthday = pat.patBirthday;
        if (patBirthday != null ) {
            update += " , " + UserPatTable.tablePatBirthday + " = '" + patBirthday + "'";
        }
        String patAddress = pat.patAddress;
        if (patAddress != null ) {
            update += " , " + UserPatTable.tablePatAddress + " = '" + patAddress + "'";
        }
        if (update.equals("")) {
            return new MsgHint("请设置要修改的参数").toJson();
        }
        if (patPhone != null && !patPhone.equals("")) {
            boolean isExit = isRegister(jdbcTemplate, patPhone);
            if (isExit) {
                return new MsgHint("该手机号已存在").toJson();
            }
        }
        update = update.replaceFirst(" , ", "");
        String sql = "UPDATE " + UserPatTable.tableName
                + " SET "
                + update
                + " WHERE "
                + UserPatTable.tablePatId + " = '" + pat.patId + "'";
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "修改成功").toJson();
        }
        return new MsgHint("修改失败").toJson();
    }

    //查询患者
    private List<UserPatsEntity> userQuery(JdbcTemplate jdbcTemplate, String sql) {
        List<UserPatsEntity> users = null;
        try {
            users = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(UserPatsEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return users;
    }

    //查询患者
    private List<UserPatLoginEntity> userQueryLogin(JdbcTemplate jdbcTemplate, String sql) {
        List<UserPatLoginEntity> users = null;
        try {
            users = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(UserPatLoginEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return users;
    }

    //创建token
    public void createTokenWx(JdbcTemplate jdbcTemplate, String patWxId, String token, String time) {
        String sql = "update  " + UserPatTable.tableName
                + " set "
                + UserPatTable.tablePatToken + " = '" + token + "'"
                + " , "
                + UserPatTable.tablePatLoninTime + " = '" + time + "'"
                + " WHERE "
                + UserPatTable.tablePatWXId + " = '" + patWxId + "'";
        jdbcTemplate.update(sql);
    }

    //创建token
    public void createToken(JdbcTemplate jdbcTemplate, String patAccount,
                            String token, String time, String pushId) {
        String pushUpdate = "";
        if (!StringUtile.isEmpty(pushId)) {
            pushUpdate = " , " + UserPatTable.tablePatPushId + " = '" + pushId + "'";
        }
        String sql = "update  " + UserPatTable.tableName
                + " set "
                + UserPatTable.tablePatToken + " = '" + token + "'"
                + " , "
                + UserPatTable.tablePatLoninTime + " = '" + time + "'"
                + pushUpdate
                + " WHERE "
                + UserPatTable.tablePatAccount + " = '" + patAccount + "'";
        jdbcTemplate.update(sql);
    }

    //校验token
    public UserPatsEntity verifyTokenUser(JdbcTemplate jdbcTemplate, String token) {
        UserPatsEntity user = null;
        if (token == null || token == "") {
            return user;
        }
        String sql = "SELECT * FROM " + UserPatTable.tableName + " WHERE "
                + UserPatTable.tablePatToken + " = '" + token + "'";
        List<UserPatsEntity> users = userQuery(jdbcTemplate, sql);

        if (users != null && users.size() > 0) {
            user = users.get(0);
        }
        if (users != null) {
            updateToken(jdbcTemplate, token);
        }
        return user;
    }

    //更新token
    private void updateToken(JdbcTemplate jdbcTemplate, String token) {
        String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
        String sql = "update  " + UserPatTable.tableName
                + " set "
                + UserPatTable.tablePatLoninTime + " = '" + loginTime + "'"
                + " WHERE "
                + UserPatTable.tablePatToken + " = '" + token + "'";
        jdbcTemplate.update(sql);
    }
}
